<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class fb extends CI_Controller {
	public function __construct(){
		parent::__construct();
		parse_str($_SERVER['QUERY_STRING'], $_REQUEST);
		$CI = & get_instance();
		$CI->config->load("facebook",TRUE);
		$config = $CI->config->item('facebook');
		$this->load->library('facebook/facebook', $config);		
	}
	
	function index(){
	
	}
	function login(){
		$fbuser = $this->facebook->getUser();
		if($fbuser) {
			
			try {
				$user_info = $this->facebook->api('/me');
				$user_id = $user_info['id'];
				//$user = $this->muser->get($user_id,'FACEBOOK_ID');
				if($user){
					//$this->muser->setLogin($user);
					//redirect(base_url());
				}
				else{
					$arr_insert = array();
					//$arr_insert['USE_ACCOUNT'] = $user_info['username'];
					//$arr_insert['USE_NAME'] = $user_info['name'];
					//$arr_insert['USE_EMAIL'] = $user_info['email'];
					//$arr_insert['FACEBOOK_ID'] = $user_info['id'];
					//$arr_insert['USE_GROUP'] = 1;
					//$arr_insert['USE_GENDER'] = $user_info['gender'];
					//$arr_insert['USE_AVATAR'] = 'http://graph.facebook.com/'.//$arr_insert['FACEBOOK_ID']. '/picture?type=normal';
					//$new_userid = $this->muser->registry($arr_insert);
					//$arr_insert['USE_ID'] = $new_userid;
					//$this->muser->setLogin((object)$arr_insert);
					redirect(base_url());
				}
			} catch(FacebookApiException $e) {
				//redirect(base_url());
			}
		} else {
		//email,publish_stream,user_birthday,read_stream, photo_upload,user_photos,user_photo_video_tags
			$login = $this->facebook->getLoginUrl(array('scope' => 'email,read_stream, photo_upload,user_photos,manage_pages'));
			redirect($login);
		}

	}
	function logout(){
		$this->load->helper('cookie');
		//$link_logout = $this->facebook->getLogoutUrl();
		$this->session->unset_userdata('fb_session');
		//$this->session->sess_destroy();
		$this->facebook->clearAllPersistentData();
		delete_cookie("kmv_cfb_".$this->facebook->getAppId());
		//redirect($link_logout);
		redirect(base_url().'dang-ky-thanh-vien.html');
	}
	
	function graph_post()
	{
	//http://golink.com:9090/xxx_page/fbci/graph_post
	$user = $this->facebook->getUser();
	//$this->auto_post_wall();
	
		if($user) {
		$this->auto_post_wall();
			try {
			//	$user_info = $this->facebook->api('/me');
			//	$this->auto_post_wall();
			} catch(FacebookApiException $e) {
			//print_r($e);
				echo "Loi";
			}
		} else {
		//email,publish_stream,user_birthday,read_stream, photo_upload,user_photos,user_photo_video_tags
			$login = $this->facebook->getLoginUrl(array('scope' => 'manage_pages, offline_access, publish_stream, photo_upload ,user_photos'));
			redirect($login);
		}
		
		//$mess = file_get_contents("https://graph.facebook.com/10151431729306961?fields=likes,comments.limit(2000).filter(stream).fields(from,id,message,created_time)");
		
		//print_r(json_decode($mess));
		
	}
	function auto_post_wall()
	{
	$this->upload_photo();
	return '';
	//page id: 579981988684245
	$album_id = 'a.587824744566636.152636.579981988684245';
	$album_id = '587824744566636';
	$path = '301873_579983158684128_832817664_n.jpg';
	$args = array(
		'message'   => 'Test auto update status at '.date("H:i:s").' by HT',
		//'link'      => 'http://golink.vn/',
		//'caption'   => 'Test auto update status at '.date("H:i:s").' by HT',
		//'image' => '@'. $path,
		//'aid' => $album_id,
	);
	//$post_id = $this->facebook->api("/golink.vn/feed", "post", $args);
	$pageID = "579981988684245"; //obtained from page's url

	$status = $this->facebook->api($pageID.'/feed', 'post', $args);

print_r($status);
	}
	
	function upload_photo()
	{
	
	$this->facebook->setFileUploadSupport(true);
	$fanpage ='163388433844589';//maccuoi
	$album_uid ='165859193597513';
	$file='TN.jpg';
	
	$accounts = $this->facebook->api('/'.$fanpage.'/?fields=access_token', 'GET', '');


 $fanpage_token = $accounts['access_token'];

$photo_details = array(
    'message'=> 'Test upload photo by htlove',
	'aid' => $album_uid,
	'access_token' => $fanpage_token,
	'source' => '@'.realpath("./")."/".$file,
);
$upload_photo = $this->facebook->api('/'.$fanpage.'/photos', 'post', $photo_details);
print_r($upload_photo);

//$this->delete_post($upload_photo['post_id'],$fanpage_token);

return '';
	}
	
	function delete_post($post_id = '',$pages_access_token){
	 $args = array(
    'access_token'  => $pages_access_token
  );
  $deleted = $this->facebook->api($post_id,"delete",$args);
  if($deleted)
  {
    echo " <font color=\"green\">OK</font><br>";
  }
  else
  {
    echo " <font color=\"red\">ERR</font><br>";
  }
	
	}
	function clicked(){
	$fbuser = $this->facebook->getUser();
		if($fbuser) {
		
			try {
				$user_info = $this->facebook->api('/me');
				$user_id = $user_info['id'];
				 $this->auto_upload_wall();
			} catch(FacebookApiException $e) {
				die("Error");
			}
		} else {
		//email,publish_stream,user_birthday,read_stream, photo_upload,user_photos,user_photo_video_tags
			$login = $this->facebook->getLoginUrl(array('scope' => 'email, publish_stream, photo_upload,user_photos'));
			redirect($login);
		}
	
	}
	function auto_upload_wall(){
	
	
	//$this->upload_photo();
	//return '';
	//page id: 579981988684245
	$album_id = 'a.587824744566636.152636.579981988684245';
	$album_id = '587824744566636';
	$path = 'imga.jpg';


 //$fanpage_token = $accounts['access_token'];
$photo_details = array(
    'message'=> 'kaka, Cám ơn bạn đã click dùm !!',
	//'aid' => $album_uid,
	//'access_token' => $fanpage_token,
	'source' => '@'.realpath("./")."/".$path,
);
$upload_photo = $this->facebook->api('/me/photos', 'post', $photo_details);

	print_r($upload_photo);
	
	}
	
	function check_like(){

	$isFan1 = $this->facebook->api(array(
  "method" => "fql.query",
  "query"  => "SELECT uid  FROM page_fan WHERE page_id = '337701336286157' AND uid = '100002508886943'"
));

$isFan = $this->facebook->api(array(
    "method"    => "pages.isFan",
    "page_id"   => '337701336286157',
    "uid"       => '100002508886943'
));
print_r($isFan1);
print_r($isFan);
	}
	
	function uploadVideo(){
	//Download file
	$filename = "video.mp4";
	set_time_limit(999999999);
 
	$url = "http://r9---sn-aigllnld.googlevideo.com/videoplayback?mt=1397407173&mws=yes&sparams=id%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&ip=2a02%3A2498%3Ae002%3A88%3A225%3A90ff%3Afe7c%3Ab806&key=yt5&upn=yklJeB76WPw&ratebypass=yes&itag=18&source=youtube&signature=245699C4E7DEB062EA9A4EC37318C771E2605C11.17AB12C8A6AEA219F53646D172269392A9FFFB76&mv=m&ipbits=0&fexp=900356%2C937417%2C913434%2C936916%2C934022%2C936923&ms=au&sver=3&id=o-ADKUo_hSoQFX94AFGVfpML5q8UznfU94i3QND84wVAn4&expire=1397429550&title=Epic+Old+Man+-+Death+Party";
	//$content = file_get_contents($url);
	//file_put_contents('./'.$filename,$content);
	
	$pagename = "maccuoicom";
	$pagename = "163388433844589";
	$this->facebook->setFileUploadSupport(true);
	// $page_info = $this->facebook->api("/".$pagename."?fields=access_token"); 
		 $img =  'D:\wamp\www\maccuoi.com\Movie.wmv.flv';     
	 
   $ret_obj = $this->facebook->api("/".$pagename."/videos", 'POST', array(
      'source' => '@'.realpath("./")."\\". $filename,
	  //'access_token'  => $page_info['access_token'],
      'title' => "This is just a test",
      'description' => 'Test upload video by HTLove Script',
      'privacy' => json_encode(array( 'value' => 'EVERYONE' )),
      )
   );
   echo '<pre>Video ID: ' . $ret_obj['id'] . '</pre>';
	}
	
	
}
?>
<?php
/*
$session = $facebook->getSession();
 
$user = $facebook->getUser();
$page = 'PAGEID';
 
// Session based API call.
if ($session) {
  try {
$likeID = $facebook->api(array( 'method' => 'fql.query', 'query' =>
'SELECT target_id FROM connection WHERE source_id =' . $user . 'AND target_id =' .$page ));
 
if ( empty($likeID) ) {
// user has NOT Liked the page
echo "Like my page!";
 
} else {
 
// user HAS Liked the page
echo "Thank you for liking my page";
 
}
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}
*/
?>